<template>
	<div class="store-chart-component" ref="content">
		<div class="chart-block" ref="charta"></div>
		<div class="desc-view">
			<div>{{dataSource.total}}</div>
			<div>总库位</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onBeforeUnmount, toRefs, getCurrentInstance, onMounted } from 'vue';
import * as echarts from 'echarts';
import { eleResize } from '@/assets/js/utils'

const instance = getCurrentInstance()

const props = defineProps({
	dataSource:{
		type:Object,
		default:function(){
			return {
				total:0,
				emptyTray:0,
				emptyLocation:0,
				goods:0,
				loaded:false
			}
		}
	}
})
const {dataSource} = toRefs(props)

let $frame = null;
let $dom = null;
let chart = null;

const defaultOption = {
	series: [
		{
			name: '库存占比',
			type: 'pie',
			radius: ['50%', '65%'],
			avoidLabelOverlap: false,
			itemStyle: {
				borderRadius: 4
			},
			label:{
				formatter: '{d}%\n{b}',
				fontSize:30,
				color:'#ffffff'
			},
			labelLine:{
				length:30
			},
			data: []
		}
	]
}

const createChart = function(callback){
	window.setTimeout(()=>{
		if (!$dom) {
			$dom = instance.refs.charta;
			chart = echarts.init($dom)
		}
		callback()
	},100)
}

const drawChart = function(){
	destoryChart()
	if (!dataSource.value.loaded) return false
	createChart(()=>{
		let opt = JSON.parse(JSON.stringify(defaultOption))
		opt.series[0].data = [
			{value:dataSource.value.emptyLocation,name:'空闲',itemStyle:{color:'#CBC6C6'}},
			{value:dataSource.value.goods,name:'存货',itemStyle:{color:'#F85707'}},
			{value:dataSource.value.emptyTray,name:'空托',itemStyle:{color:'#7BC250'}}
		];
		chart.setOption(opt)
	})	
}

const destoryChart = function(){
	try{
		chart.dispose();
		$dom.innerHTML = '';
		chart = null;
		$dom = null;
	}catch(e){
		//TODO handle the exception
	}
}

/* 创建div宽高变化监听器 */
const createEleResize = function(){
	$frame = instance.refs.content;
	eleResize.on($frame, drawChart);
}

/* div宽高变化事件移除 */
const destroyEleResize=function(){
	try{
		eleResize.off($frame, drawChart);
		$frame = null
	}catch(e){
		//TODO handle the exception
	}
}

onMounted(()=>{
	createEleResize()
})

onBeforeUnmount(()=>{
	destroyEleResize()
	destoryChart()
})

defineExpose({drawChart})
</script>

<style scoped lang="scss">
.store-chart-component{
	height: 100%;
	position: relative;
	.chart-block,.desc-view{
		height: 100%;
		width: 100%;
	}
	.desc-view{
		position: absolute;
		z-index: 1000;
		background: transparent;
		top: 0;
		left: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 1.2em;
		line-height: 1.2em;
		color: #fff;
		font-weight: bold;
	};
}
</style>